package community.hospital.aspect;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import community.hospital.util.JwtUtil;
import community.hospital.util.RedisUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

import static community.hospital.common.Constant.TOKEN_NAME;
import static community.hospital.common.RedisConstant.*;

/**
 * @Author：ydj
 * @Date：2023/1/20 0:07
 */
@Aspect
@Component
@Order(1)
public class RefreshTokenExpireAspect {
    @Resource
    private RedisUtil redisUtil;

    @Pointcut(value = "execution(* community.hospital.controller..*(..))")
    public void pointcut() {

    }

    @Before(value = "pointcut()")
    public void refreshAspect() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        if (request == null) {
            return;
        }
        String value = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(value)) {
            return;
        }
        Long userId = JwtUtil.getUserId(value);
        String loginUserKey = LOGIN_USER + SPLIT + userId;
        if (redisUtil.get(loginUserKey)==null) {
            return;
        }
        //刷新token的时间
        redisUtil.expire(loginUserKey, USER_PERSISTENCE_TIME, TimeUnit.SECONDS);

    }
}
